//
//  MainPageReplyCell.swift
//  Gaoloumi
//
//  Created by Jasper on 4/10/16.
//  Copyright © 2016 Jasper. All rights reserved.
//

import UIKit
import SDWebImage

class MainPageReplyCell: UITableViewCell, SDPhotoBrowserDelegate {

    
    @IBOutlet weak var userImageView: UIImageView!
    @IBOutlet weak var cityLabel: UILabel!
    @IBOutlet weak var titleLabel: UILabel!
    @IBOutlet weak var imageView1: UIImageView!
    @IBOutlet weak var imageView2: UIImageView!
    @IBOutlet weak var imageView3: UIImageView!
    @IBOutlet weak var userButton: UIButton!
    @IBOutlet weak var updateTimeLabel: UILabel!
    @IBOutlet weak var imageHeight: NSLayoutConstraint!
    
    @IBOutlet weak var replyContentLabel: UILabel!
    @IBOutlet weak var replyUserLabel: UILabel!
    @IBOutlet weak var replyUpTimeLabel: UILabel!
    
    var cellReply: Reply?
    
    override func awakeFromNib() {
        super.awakeFromNib()
      
        userImageView.layer.cornerRadius = 3
        userImageView.layer.masksToBounds = true
        
        
        let tap = UITapGestureRecognizer(target: self, action: #selector(MainPageReplyCell.tapGesture(_:)))
        imageView1.addGestureRecognizer(tap)
        let tap2 = UITapGestureRecognizer(target: self, action: #selector(MainPageReplyCell.tapGesture(_:)))
        imageView2.addGestureRecognizer(tap2)
        let tap3 = UITapGestureRecognizer(target: self, action: #selector(MainPageReplyCell.tapGesture(_:)))
        imageView3.addGestureRecognizer(tap3)
    }
    
    
    func refreshView(_ reply: Reply) {
        cellReply = reply
        
        userButton.setTitle(reply.user?.username, for: .normal)
        titleLabel.text = reply.content
        let imgFile = reply.city!.iconImage // 城市头像
        
        let url = URL(string: (imgFile?.url)!)
        userImageView?.kf.setImage(with: url,
                                    placeholder: DataCenter.sharedInstance.placeholderImage,
                                    options: nil,
                                    progressBlock: { receivedSize, totalSize in
                                        
            },
                                    completionHandler: { image, error, cacheType, imageURL in
                                        
        })
        
        cityLabel.text = reply.city?.name
        
        let date = reply.object(forKey: "updatedAt") as! Date
        updateTimeLabel.text = DataCenter.sharedInstance.friendlyTime(date)
        
        var imgArray = [imageView1, imageView2, imageView3]
        var i = 0
        if reply.contentImage == nil || reply.contentImage?.count == 0 {
            imageHeight.constant = 0
        } else {
            let width = (UIScreen.main.bounds.width-8*4)/3
            let intWidth = Int(width)*2
            imageHeight.constant = width
            for image in reply.contentImage! {
                let urlstr = image.url
                if urlstr != nil {
                    let urlCon = "\(urlstr)?imageView/1/w/\(intWidth)/h/\(intWidth)"
                    let imageView = imgArray[i]
                    
                    let url = URL(string: urlCon)
                    imageView?.kf.setImage(with: url,
                                               placeholder: DataCenter.sharedInstance.placeholderImage,
                                               options: nil,
                                               progressBlock: { receivedSize, totalSize in
                                                
                        },
                                               completionHandler: { image, error, cacheType, imageURL in
                                                
                    })
                    
                    i += 1
                    imageView?.isUserInteractionEnabled = true
                }
            }
        }
        
        imgArray.removeSubrange(Range(0..<i))
        for imageView in imgArray {
            imageView?.image = nil
            imageView?.isUserInteractionEnabled = false
        }
        
        replyContentLabel.text = reply.topic?.title
        replyUserLabel.text = reply.topic?.userName
        
        let repDate = reply.topic!.object(forKey: "createdAt") as! Date
        replyUpTimeLabel.text = DataCenter.sharedInstance.friendlyTime(repDate)
    }
    
    func tapGesture(_ sender: UITapGestureRecognizer) {
        let browser = SDPhotoBrowser()
        browser.sourceImagesContainerView = self.contentView
        browser.imageCount = (cellReply!.contentImage?.count)!
        browser.currentImageIndex = ((sender.view?.tag)!-100)
        browser.delegate = self
        browser.show()
    }
    
    func photoBrowser(_ browser: SDPhotoBrowser!, placeholderImageFor index: Int) -> UIImage! {
        
        let img = self.contentView.viewWithTag(100+index) as! UIImageView
        return img.image
        
//        let url = cellReply?.contentImage![index].url
//        let manager = SDWebImageManager.sharedManager()
//        if manager.diskImageExistsForURL(NSURL.fileURLWithPath(url!)) {
//            let data = NSData(contentsOfURL: NSURL.fileURLWithPath(url!))
//            return UIImage(data: data!)
//        } else {
//            
//        }
    }
    
    func photoBrowser(_ browser: SDPhotoBrowser!, highQualityImageURLFor index: Int) -> URL! {
        let url = cellReply?.contentImage![index].url
        return URL(string: url!)
    }
}
